#region Using

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;

using Gizmox.WebGUI.Forms;
using System.Text.RegularExpressions;
using TVC.Layout;
using FlexCel.Core;
using System.IO;
using Gizmox.WebGUI.Common.Gateways;

#endregion

namespace TVC.Forms
{
    public partial class frmCommand : Form
    {
        DTO.LIST_CMDInfo cmdInf;
        string sErr = "";
        readonly Dictionary<string, Control> arrControl = new Dictionary<string, Control>();
        public MainForm MainForm { get; set; }
        public frmCommand(MainForm form)
        {
            InitializeComponent();
            MainForm = form;
        }
        public frmCommand(string args, MainForm form)
        {
            InitializeComponent();
            InitCommand(args);
            MainForm = form;
        }
        public frmCommand(Dictionary<string, object> args, MainForm form)
        {
            InitializeComponent();
            InitCommand(args);
            MainForm = form;
        }
        public frmCommand(Gizmox.WebGUI.Common.Interfaces.IContext objContext)
            : base(objContext)
        {

        }

        public void InitCommand(Dictionary<string, object> dic)
        {
            if (dic.ContainsKey("id"))
            {
                BUS.LIST_CMDControl cmdCtr = new BUS.LIST_CMDControl();
                cmdInf = cmdCtr.Get(MainForm.DB, dic["id"].ToString(), ref sErr);
                Text = String.Format("Command: {0} - {1}", cmdInf.CmdID, cmdInf.Description);
                if (cmdInf.CmdID != "")
                {
                    DataRow row = cmdInf.ToDataRow(DTO.LIST_CMDInfo.ToDataTable());
                    InitParam(1, row, dic);
                    InitParam(2, row, dic);
                    InitParam(3, row, dic);
                    InitParam(4, row, dic);
                    InitParam(5, row, dic);
                    InitParam(6, row, dic);
                    InitParam(7, row, dic);
                    InitParam(8, row, dic);
                    InitParam(9, row, dic);
                    InitParam(10, row, dic);
                }
            }

        }
        public void InitCommand(string args)
        {

            Dictionary<string, object> dic = new Dictionary<string, object>();
            string[] arrParam = args.Split('&');
            if (arrParam != null)
                foreach (string it in arrParam)
                {
                    string[] value = it.Split('=');
                    if (value != null)
                    {
                        if (value.Length == 2)
                        {
                            dic.Add(value[0], value[1]);
                        }
                    }
                }
            if (dic.ContainsKey("id"))
            {
                BUS.LIST_CMDControl cmdCtr = new BUS.LIST_CMDControl();
                cmdInf = cmdCtr.Get(MainForm.DB, dic["id"].ToString(), ref sErr);
                Text = String.Format("Command: {0} - {1}", cmdInf.CmdID, cmdInf.Description);
                if (cmdInf.CmdID != "")
                {
                    DataRow row = cmdInf.ToDataRow(DTO.LIST_CMDInfo.ToDataTable());
                    InitParam(1, row, dic);
                    InitParam(2, row, dic);
                    InitParam(3, row, dic);
                    InitParam(4, row, dic);
                    InitParam(5, row, dic);
                    InitParam(6, row, dic);
                    InitParam(7, row, dic);
                    InitParam(8, row, dic);
                    InitParam(9, row, dic);
                    InitParam(10, row, dic);
                }
            }

        }

        private void InitParam(int p, DataRow cmdInf, Dictionary<string, object> dic)
        {
            if (cmdInf["P" + p].ToString() != "")
            {
                Label lb = new Label(cmdInf["P" + p].ToString()) { Name = "lblP" + p };
                Controls.Add(lb);
                lb.Location = new Point(9, 11 + (p - 1) * 25);
                string value;
                if (dic.ContainsKey("P" + p))
                    value = dic["P" + p].ToString();
                else
                    value = "";

                if (cmdInf["L_P" + p].ToString() == "")
                {
                    TextBox tx = new TextBox()
                    {
                        Name = "txtP" + p
                        ,
                        Location = new Point(109, 8 + (p - 1) * 25)
                    };
                    Controls.Add(tx);
                    tx.Width = 500;
                    arrControl.Add("P" + p, tx);
                    if (dic.ContainsKey("P" + p))
                    {
                        tx.Text = dic["P" + p].ToString();
                    }
                }
                else if (cmdInf["L_P" + p].ToString() == "Date" || cmdInf["L_P" + p].ToString() == "SDN")
                {
                    DateTimePicker dp = new DateTimePicker()
                    {
                        Name = "dtpP" + p
                        ,
                        Format = DateTimePickerFormat.Custom
                        ,
                        CustomFormat = "dd/MM/yyyy"
                        ,
                        Location = new Point(109, 8 + (p - 1) * 25)
                        ,
                        Tag = cmdInf["L_P" + p].ToString()
                    };
                    Controls.Add(dp);
                    arrControl.Add("P" + p, dp);

                    if (dic.ContainsKey("P" + p))
                    {
                        if (cmdInf["L_P" + p].ToString() == "Date")
                            dp.Value = Convert.ToDateTime(dic["P" + p].ToString());
                        else
                        {
                            dp.Value = BUS.CommonControl.ConvertIntToDate(Convert.ToInt32(dic["P" + p].ToString())).Value;
                        }
                    }
                }
                else if (cmdInf["L_P" + p].ToString() == "SDN")
                {
                    MaskedTextBox mtb = new MaskedTextBox()
                    {
                        Name = "mtbP" + p
                        ,
                        Location = new Point(109, 8 + (p - 1) * 25)
                        ,
                        Mask = "000/0000"
                    };
                    Controls.Add(mtb);
                    arrControl.Add("P" + p, mtb);

                    if (dic.ContainsKey("P" + p))
                    {
                        mtb.Text = BUS.CommonControl.GetPeriodString(Convert.ToInt32(dic["P" + p].ToString()));
                    }
                }
                else if (cmdInf["L_P" + p].ToString() == "N")
                {
                    TextBox tx = new TextBox()
                    {
                        Name = "txtP" + p,
                        Location = new Point(109, 8 + (p - 1) * 25),
                        Tag = cmdInf["L_P" + p].ToString(),
                        Width = 500
                    };
                    tx.Validating += (sender, e) =>
                    {
                        if (!IsNumber(tx.Text))
                        {
                            e.Cancel = true;
                        }
                    };

                    if (dic.ContainsKey("P" + p))
                    {
                        tx.Text = dic["P" + p].ToString();
                    }

                    Controls.Add(tx);
                    arrControl.Add("P" + p, tx);
                }
                else
                {
                    Modules.CustomControl.MultiColumnCombo mcb = new Modules.CustomControl.MultiColumnCombo()
                    {
                        Name = "mcbP" + p,
                        Location = new Point(109, 8 + (p - 1) * 25),
                        Tag = cmdInf["L_P" + p].ToString()
                    };

                    mcb.Width = 200;
                    DataTable dt = null;
                    BUS.CategoryControl cateCtr = new BUS.CategoryControl();
                    DTO.CategoryInfo cateinfo = cateCtr.Get(MainForm.DB, cmdInf["L_P" + p].ToString(), ref sErr);
                    if (cateinfo.Code != "")
                    {
                        if (cateinfo.QdCode == "")
                        {
                            if (!MainForm.IsContainsTables("LKC"))
                                MainForm.LoadDataTable("LKC");
                            DataRow[] arr = MainForm.GetTable("LKC").Select(String.Format("Category='{0}'", cmdInf["L_P" + p]));
                            dt = MainForm.GetTable("LKC").Clone();
                            foreach (DataRow row in arr)
                            {
                                dt.Rows.Add(row.ItemArray);
                            }
                        }
                        else
                        {
                            dt = MainForm.LoadQDSource(MainForm.DB, cateinfo);
                        }

                        mcb.Binding = dt;
                        GridLayout layout = layout = new GridLayout(MainForm.ServerPath + "Resources\\Layout\\", String.Format("{0}Documents\\Layout\\{1}\\", MainForm.ServerPath, MainForm.PODInfo.USER_ID), "LKC");
                        MainForm.InitMultiComboBox(mcb, layout, "Description", "Code");
                    }
                    else
                    {
                        GridLayout layout = layout = new GridLayout(MainForm.ServerPath + "Resources\\Layout\\", String.Format("{0}Documents\\Layout\\{1}\\", MainForm.ServerPath, MainForm.PODInfo.USER_ID), cmdInf["L_P" + p].ToString());
                        if (!MainForm.IsContainsTables(cmdInf["L_P" + p].ToString()))
                            MainForm.LoadDataTable(cmdInf["L_P" + p].ToString());
                        mcb.Binding = MainForm.GetTable(cmdInf["L_P" + p].ToString());
                        MainForm.InitMultiComboBox(mcb, layout, layout.LColumn[1].DataPropertyName, layout.LColumn[0].DataPropertyName);
                    }
                    if (dic.ContainsKey("P" + p))
                    {
                        mcb.Value = dic["P" + p].ToString();
                    }
                    Controls.Add(mcb);
                    arrControl.Add("P" + p, mcb);
                }
            }
        }
        public static bool IsNumber(string pText)
        {
            Regex regex = new Regex(@"^[-+]?[0-109]*\.?[0-109]+$");
            return regex.IsMatch(pText);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Dictionary<string, object> lVal = GetListValue();

            RunCommand(this, lVal, cmdInf);
            DialogResult = Gizmox.WebGUI.Forms.DialogResult.OK;
            Close();
        }

        public static void RunCommand(ContainerControl frm, Dictionary<string, object> lVal, DTO.LIST_CMDInfo cmdInf)
        {
            using (DataSet _dset = new DataSet())
            {
                Report.ReportGenerator rg = new Report.ReportGenerator(_dset, "CMD_" + cmdInf.Template, cmdInf.DTB, MainForm.ReportConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", MainForm.ServerPath + "Documents\\") { ValueList = lVal };
                ExcelFile xlsFile = rg.CreateReport();


                if (cmdInf.IsSave == "Y")
                {
                    //xlsFile.Save(String.Format("{0}Report\\CMD_{1}.xls", MainForm.ServerPath, cmdInf.Template));

                    MemoryStream ms = new MemoryStream();

                    xlsFile.Save(ms);
                    DownloadGateway myDownload = new DownloadGateway(ms, String.Format("{0}Report\\CMD_{1}.xls", MainForm.ServerPath, cmdInf.Template));

                    myDownload.ContentType = "application/vnd.ms-excel";
                    myDownload.StartDownload(frm);
                }
                else
                {

                    TXlsNamedRange range = xlsFile.GetNamedRange(cmdInf.Range, 0);
                    if (range != null)
                    {
                        xlsFile.ActiveSheet = range.SheetIndex;

                        for (int i = 0; i < range.ColCount; i++)
                        {
                            object header = xlsFile.GetCellValue(range.Top, range.Left + i);
                            if (header != null && header.ToString() == cmdInf.CmdText)
                            {
                                for (int k = 1; k < range.RowCount; k++)
                                {
                                    object script = xlsFile.GetCellValue(range.Top + k, range.Left + i);
                                    if (script != null && !string.IsNullOrEmpty(script.ToString()))
                                    {
                                        BUS.CommonControl ctr = new BUS.CommonControl();
                                        ctr.executeNonQuery(script.ToString());
                                    }
                                }
                            }
                        }
                    }
                }

            }
        }

        private Dictionary<string, object> GetListValue()
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            foreach (KeyValuePair<string, Control> it in arrControl)
            {
                if (it.Value is TextBox)
                {
                    result.Add(it.Key, it.Value.Text);
                }
                else if (it.Value is DateTimePicker)
                {
                    DateTime dt = ((DateTimePicker)it.Value).Value;
                    if (it.Value.Tag == "Date")
                        result.Add(it.Key, dt.ToString("yyyy-MM-dd"));
                    else
                    {
                        result.Add(it.Key, dt.Year * 10000 + dt.Month * 100 + dt.Day);
                    }
                }
                else if (it.Value is MaskedTextBox)
                {
                    int per = BUS.CommonControl.ConvertStringToPeriod(it.Value.Text);
                    result.Add(it.Key, per);
                }
                else if (it.Value is MaskedTextBox)
                {
                    int per = BUS.CommonControl.ConvertStringToPeriod(it.Value.Text);
                    result.Add(it.Key, per);
                }
                else if (it.Value is Modules.CustomControl.MultiColumnCombo)
                {
                    int per = BUS.CommonControl.ConvertStringToPeriod(it.Value.Text);
                    result.Add(it.Key, ((Modules.CustomControl.MultiColumnCombo)it.Value).Value);
                }
            }
            return result;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}